package org.example.trainTicketSystem.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.trainTicketSystem.DTO.RefundRecordDTO;
import org.example.trainTicketSystem.entity.RefundRecord;
import org.example.trainTicketSystem.entity.SaleRecord;
import org.example.trainTicketSystem.entity.Ticket;
import org.example.trainTicketSystem.service.RefundRecordService;
import org.example.trainTicketSystem.service.SaleRecordService;
import org.example.trainTicketSystem.service.TicketService;
import org.example.trainTicketSystem.utils.ResponseResult;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/api/refunds")
@RequiredArgsConstructor
public class RefundRecordController {

    private final RefundRecordService refundRecordService;
    private final SaleRecordService saleRecordService;
    private final TicketService ticketService;

    @PostMapping()
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<RefundRecord> addRefundRecord(
            @Valid @RequestBody RefundRecordDTO refundRecordDTO,
            HttpServletRequest request) {

        // 获取当前登录用户
        Integer currentUserId = (Integer) request.getAttribute("userId");
        if (currentUserId == null) {
            log.warn("Unauthorized refund attempt");
            return ResponseResult.fail("未登录用户无法退票");
        }

        try {
            // 验证销售记录
            SaleRecord saleRecord = saleRecordService.getById(refundRecordDTO.getSaleId());
            if (saleRecord == null) {
                log.warn("Sale record not found: {}", refundRecordDTO.getSaleId());
                return ResponseResult.fail("该售票记录不存在");
            }

            // 检查是否是本人的车票
            if (!saleRecord.getUserId().equals(currentUserId)) {
                log.warn("Refund attempt for ticket not owned by user: userId={}, saleId={}",
                        currentUserId, refundRecordDTO.getSaleId());
                return ResponseResult.fail("只能退回自己购买的车票");
            }

            // 验证车票
            Ticket ticket = ticketService.getById(saleRecord.getTicketId());
            if (ticket == null) {
                log.warn("Ticket not found: {}", saleRecord.getTicketId());
                return ResponseResult.fail("该车票不存在");
            }

            // 检查车票状态
            if (!"SOLD".equalsIgnoreCase(ticket.getStatus())) {
                log.warn("Invalid ticket status for refund: status={}, ticketId={}",
                        ticket.getStatus(), ticket.getTicketId());
                return ResponseResult.fail("该车票状态不允许退票");
            }

            // 更新车票状态
            ticket.setStatus("REFUNDED");

            // 创建退款记录
            RefundRecord refundRecord = new RefundRecord(refundRecordDTO);

            // 原子性操作：更新车票和保存退款记录
            boolean updateTicketResult = ticketService.updateById(ticket);
            boolean saveRefundRecordResult = refundRecordService.save(refundRecord);

            if (updateTicketResult && saveRefundRecordResult) {
                log.info("Ticket refunded successfully: userId={}, saleId={}, ticketId={}",
                        currentUserId, refundRecordDTO.getSaleId(), ticket.getTicketId());
                return ResponseResult.success("退款成功", refundRecord);
            } else {
                log.error("Failed to complete ticket refund: userId={}, saleId={}",
                        currentUserId, refundRecordDTO.getSaleId());
                return ResponseResult.fail("退票失败，请稍后重试");
            }

        } catch (Exception e) {
            log.error("Error processing ticket refund", e);
            return ResponseResult.fail("退票处理发生错误");
        }
    }

    @GetMapping("/{saleId}")
    public ResponseResult<Page<RefundRecord>> getRefundRecords(
            @PathVariable int saleId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            HttpServletRequest request) {

        // 获取当前登录用户
        Integer currentUserId = (Integer) request.getAttribute("userId");

        // 验证销售记录是否属于当前用户
        SaleRecord saleRecord = saleRecordService.getById(saleId);
        if (saleRecord == null) {
            log.warn("Sale record not found: {}", saleId);
            return ResponseResult.fail("售票记录不存在");
        }

        // 权限检查：只能查询自己的退票记录
        if (!saleRecord.getUserId().equals(currentUserId)) {
            log.warn("Unauthorized refund record access: currentUser={}, saleId={}",
                    currentUserId, saleId);
            return ResponseResult.fail("无权查看该销售记录的退票信息");
        }

        // 规范化分页参数
        page = Math.max(1, page);
        size = Math.min(Math.max(1, size), 100);

        try {
            Page<RefundRecord> refundRecords = refundRecordService.getRefundRecordsBySaleId(saleId, page, size);

            if (refundRecords.getRecords().isEmpty()) {
                log.info("No refund records found for sale record: {}", saleId);
                return ResponseResult.success("暂无退票记录", refundRecords);
            }

            log.info("Refund records retrieved successfully: saleId={}, page={}, total={}",
                    saleId, page, refundRecords.getTotal());
            return ResponseResult.success("退票记录查找成功", refundRecords);

        } catch (Exception e) {
            log.error("Error retrieving refund records", e);
            return ResponseResult.fail("获取退票记录失败");
        }
    }
}